package com.seele.tigerwallet.ui.activtiy;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.Constant;
import com.j256.ormlite.dao.GenericRawResults;
import com.seele.tigerwallet.R;
import com.seele.tigerwallet.api.APIException;
import com.seele.tigerwallet.api.APIListCallBack;
import com.seele.tigerwallet.api.APIModule;
import com.seele.tigerwallet.api.APIObjectCallBack;
import com.seele.tigerwallet.model.AssetsModel;
import com.seele.tigerwallet.model.GasInfo;
import com.seele.tigerwallet.model.GasModel;
import com.seele.tigerwallet.model.NonceModel;
import com.seele.tigerwallet.model.TranscationModel;
import com.seele.tigerwallet.model.TransferErrorModel;
import com.seele.tigerwallet.model.UserInfo;
import com.seele.tigerwallet.ui.application.SeeleApplication;
import com.seele.tigerwallet.ui.base.ToolbarBaseActivity;
import com.seele.tigerwallet.ui.event.RefreshEvent;
import com.seele.tigerwallet.ui.manager.DaoManager;
import com.seele.tigerwallet.ui.orm.GenericRowMapper;
import com.seele.tigerwallet.ui.popupwindow.PwdPopupWindow;
import com.seele.tigerwallet.ui.utils.BaseUtil;
import com.seele.tigerwallet.ui.utils.DataUtils;
import com.seele.tigerwallet.ui.utils.GsonUtil;
import com.seele.tigerwallet.ui.utils.SPUtils;
import com.seele.tigerwallet.ui.views.TransferEditext;
import com.seele.tigerwallet.ui.views.TransferSeekBar;
import com.seele.tigerwallet.utils.Constants;
import com.seele.tigerwallet.utils.EthWalletUtil;
import com.seele.tigerwallet.utils.SeeleFileMap;
import com.seele.tigerwallet.utils.Utils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;


/**
 * Description:转账界面
 * Data: 2018/6/11 11:24
 * author:
 */
public class TransferTokenActivity extends ToolbarBaseActivity implements View.OnClickListener {


    private TextView mStartTransferBtn;//下一步
    private EditText mEtToAddress;   //收款人钱包地址
    private TransferEditext mEtValue; //转账数量
    private EditText mEtContent;      //备注
    private ImageView mRightImg;        //二维码
    private TransferSeekBar mSeekBarGas;     //gas费用
    private TextView mTvSeekBarValue; //gas费用 eth值
    private TextView mCurrentBalanceTv; // 余额
    private ImageView mContactsImg;   //联系人
    //private ImageView mRefresh;   //刷新


    private int mNonceId;
    private int mGasLimit = 65000;
    private AssetsModel mAssetsModel;
    private Map<String, String> mQrResultMap;
    private PopupWindow mPwdPopupWindow;
    private String mContactAddress;
    private String mSymbolName;
    private int mSymbolId;
    private String address;//转账地址
    private String value;//转账金额
    private String note;//转账备注
    private boolean isFormQRcode = false;
    private double mLocalValue;//本地含有的token金额
    private AssetsModel mEthAssetsModel;
    private double mEthPrice;
    private double mEthBalance; // ETH值
    private double mEditShowValue; // EditText显示的真实值
    private boolean mClearValue = false;
    private List<GasModel> mGasModel;
    private int flag = 0;
    private int cout = 5;
    private long dif = 60000 * 60 * 2;
    private static final String TAG = TransferTokenActivity.class.getSimpleName();

    @Override
    public int getContainerViewId() {
        return R.layout.activity_transfer_token;
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                if (msg.what == Constants.CMD_SENDTRASLATION_SUCCESS) {
                    TranscationModel transcation = (TranscationModel) msg.obj;
                    UserInfo.get().setToken(transcation.token);
                    if (transcation.tscode == 0) { //提交转账成功
                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(TransferTokenActivity.class.getSimpleName(), transcation);
                        intent.putExtras(bundle);
                        setResult(RESULT_OK, intent);
                        Log.i(TAG, "sendTranscation success, finish.");
                        SeeleFileMap.putLong(address + value, System.currentTimeMillis());
                        TransferTokenActivity.this.dismissLoadingDialog();
                        TransferTokenActivity.this.finish();
                        Toast.makeText(SeeleApplication.getInstance(), R.string.transfer_commit_success, Toast.LENGTH_SHORT).show();
                    } else {
                        getNonceId();
                        TransferTokenActivity.this.dismissLoadingDialog();
                        showAlertDialog(R.string.transfer_commit_failed, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                        Log.e(TAG, "sendTranscation submit error." + transcation.message);
                    }
                } else if (msg.what == Constants.CMD_INPUTPASSWORD_END) {
                    String password = (String) msg.obj;
                    boolean isTransfer = true;
                    String value = SPUtils.getString(SPUtils.TRANSFER_TIME);
                    if (!TextUtils.isEmpty(value)) {

                        TransferErrorModel transferErrorModel = GsonUtil.parseJsonWithGson(value, TransferErrorModel.class);
                        if (transferErrorModel.isError) {//曾经输错过密码
                            long timeMillis = System.currentTimeMillis();
                            if (timeMillis - transferErrorModel.time < dif) {
                                isTransfer = false;
                            } else {
                                isTransfer = true;
                            }
                        } else {
                            isTransfer = true;
                        }
                    }
                    if (!isTransfer) {
                        toast();
                        return;
                    }

                    new TransferTask(password).execute();
                } else if (msg.what == Constants.CMD_UPDATE_GASINFO) {
                    List<GasModel> listsGas = (List<GasModel>) msg.obj;
                    setGasInfo(listsGas);
                }
            } catch (Exception e) {
                Log.e(TAG, "handleMessage failed:" + e.getMessage());
            }
        }
    };


    @Override
    protected void initView() {
        try {
            mStartTransferBtn = findViewById(R.id.btn_start_transfer);
            mStartTransferBtn.setOnClickListener(this);
            mEtToAddress = findViewById(R.id.et_address);
            mContactsImg = findViewById(R.id.iv_contact);
            mContactsImg.setOnClickListener(this);
            mEtValue = findViewById(R.id.et_token_value);
            mEtValue.addTextChangedListener(new ValueTextWatcher());
            mEtValue.setDecimalNumber(6);
            mEtValue.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
            mCurrentBalanceTv = findViewById(R.id.tv_token_value);
            flag = 0;
            mEtContent = findViewById(R.id.et_token_content);
            setRightImg(R.drawable.scan_translation);
            mCurrentBalanceTv.setOnClickListener(this);
            mTvSeekBarValue = findViewById(R.id.tv_seekbar_gas_value);
            //mTvSeekBarValue.setTypeface(font);
            mSeekBarGas = (TransferSeekBar) findViewById(R.id.seekbar_gas);

            handleQrResult();
            loadGasInfo();
            getGasInfo(mSymbolId);

            mSeekBarGas.setOnSeekBarChangeListener(new TransferSeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, float progress, boolean fromUser) {
                    Log.i(TAG, "progress:" + progress + "," + mSeekBarGas.getTransferProgress());
                    double value = progress;
                    double floatGas = 0.0f;
                    if (mAssetsModel.symbol.equals("ETH")) {
                        floatGas = value * 21000 * 0.000000001f;
                    } else {
                        floatGas = value * mGasLimit * 0.000000001f;
                    }
                    if (mAssetsModel.symbol.equals("ETH") && !TextUtils.isEmpty(mEtValue.getText().toString()) && fromUser) {
                        mEditShowValue = DataUtils.getDoubleValue(mEtValue.getText().toString());
                        double addValue = floatGas + mEditShowValue;
                        if (addValue > mEthBalance) {
                            mEditShowValue = mEthBalance - floatGas;
                            Log.i(TAG, "mEditShowValue:" + String.format("%f", mEditShowValue));
                            if (mEditShowValue >= 0) {
                                mEtValue.setText(DataUtils.getFourDecimal(mEditShowValue));
                            }
                        }
                    }
                    setGasValue(value);
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {

                }
            });

            //获取数据库中的资产
            try {
                if (isFormQRcode) {
                    GenericRawResults<AssetsModel> rawResults = DaoManager.getAssetsDao().queryRaw(getSql(UserInfo.get().address, mSymbolName), new GenericRowMapper(AssetsModel.class));
                    List<AssetsModel> assetsModelList = rawResults.getResults();
                    rawResults.close();
                    if (null != assetsModelList && assetsModelList.size() == 1) {
                        AssetsModel assetsModel = assetsModelList.get(0);
                        mLocalValue = DataUtils.getDoubleValue(assetsModel.balance);
                        mSymbolId = assetsModel.id;
                        mContactAddress = assetsModel.addr;
                        String showValue = DataUtils.getFourDecimal(assetsModel.balance);
                        mCurrentBalanceTv.setText(getResources().getString(R.string.current_balance) + showValue);//设置余额
                    }
                    getNonceId();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                GenericRawResults<AssetsModel> rawResults = DaoManager.getAssetsDao().queryRaw(getSql(UserInfo.get().address, "ETH"), new GenericRowMapper(AssetsModel.class));
                List<AssetsModel> assetsModelList = rawResults.getResults();
                rawResults.close();
                if (null != assetsModelList && assetsModelList.size() == 1) {
                    AssetsModel assetsModel = assetsModelList.get(0);
                    mEthAssetsModel = assetsModelList.get(0);
                    Log.i(TAG, "get ETH model:" + mEthAssetsModel.balance);
                    mEthBalance = DataUtils.getDoubleValue(assetsModel.balance);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            setGasValue(mGasModel.get(1).price);
            mEtValue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (!hasFocus) {
                        if (mAssetsModel.symbol.equals("ETH")) {
                            String value = mEtValue.getText().toString();
                            if (TextUtils.isEmpty(value)) {
                                return;
                            }
                            mEditShowValue = DataUtils.getDoubleValue(value);
                            double etValue = DataUtils.getDoubleValue(mEtValue.getText().toString());
                            double gasValue = mSeekBarGas.getTransferProgress() * 21000 * 0.000000001f;

                            if ((etValue + gasValue) > mLocalValue) {
                                mEditShowValue = mLocalValue - gasValue;
                                if (mEditShowValue > 0) {
                                    mEtValue.setText(DataUtils.getFourDecimal(mEditShowValue));
                                    Toast.makeText(TransferTokenActivity.this, getResources().getString(R.string.transfer_gas), Toast.LENGTH_LONG).show();
                                } else {
                                    mEtValue.setText("0.0");
                                    mEditShowValue = 0.0f;
                                    //Toast.makeText(TransferTokenActivity.this, getResources().getString(R.string.eth_low), Toast.LENGTH_LONG).show();
                                }
                            }
                        }
                    }
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "initView failed:" + e.getMessage());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateValue();
    }


    @Override
    protected void onRightImg() {
        startQrCode();
        super.onRightImg();
    }


    //设置汇率
    private void setGasValue(double gasValue) {
        if (mEthAssetsModel == null) {
            return;
        }
        if (gasValue < 2) {
            gasValue = 2;
        }
        try {
            double floatGas = 0.0f;
            if (mAssetsModel.symbol.equals("ETH")) {
                floatGas = gasValue * 21000 * 0.000000001f;
            } else {
                if (mGasLimit == 0) {
                    mGasLimit = 65000;
                }
                floatGas = gasValue * mGasLimit * 0.000000001f;
            }
            double gasValueUsd = floatGas * DataUtils.getDoubleValue(mEthAssetsModel.price);
            if (DataUtils.isCNY()) {
                gasValueUsd = gasValueUsd * DataUtils.getDoubleValue(UserInfo.get().exchangerate);
            }

            String sbValue = String.format("%.8f ETH", floatGas) + " ≈ " + (DataUtils.isCNY() ? "￥" : "$") + String.format("%.2f", gasValueUsd);
            mTvSeekBarValue.setText(sbValue);
            Log.e(TAG, "setGasValue:" + sbValue);
        } catch (Exception e) {
            Log.e(TAG, "setGasValue exp:" + e.getMessage());
        }


    }


    public String getSql(String address, String symbol) {
        String sql = String.format("SELECT * FROM t_assets WHERE address = '%s' AND symbol='%s'", address, symbol);
        Log.e("getSql", "::" + sql);
        return sql;
    }

    public String update(String balance, String address) {
        String sql = String.format("UPDATE t_assets SET balance = '%s' WHERE address ='%s", balance, address);

        return sql;
    }

    @Override
    public void onClick(View view) {
        try {
            switch (view.getId()) {
                case R.id.btn_start_transfer:
                    getTransferInfo();
                    break;
                case R.id.right_img://二维码扫描
                    startQrCode();
                    break;
                case R.id.iv_contact:
                    Bundle bundle = new Bundle();
                    bundle.putInt(ContactsActivity.class.getSimpleName(), ContactsActivity.SOURCE_TRANSFER);
                    Intent intent = new Intent(TransferTokenActivity.this, ContactsActivity.class);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, Constant.REQ_CONTACT_CODE);
                    break;
                case R.id.tv_token_value:
                    if (mClearValue) {
                        mEtValue.setText("");
                        mEditShowValue = 0.0f;
                        mClearValue = false;
                    } else {
                        if (mAssetsModel.symbol.equals("ETH")) {
                            double gasValue = mSeekBarGas.getTransferProgress() * 21000 * 0.000000001f;
                            mEditShowValue = mLocalValue - gasValue;
                            if (mEditShowValue > 0) {
                                Toast.makeText(this, getResources().getString(R.string.transfer_gas), Toast.LENGTH_LONG).show();
                            } else if (mEditShowValue <= 0) {
                                //Toast.makeText(this, getResources().getString(R.string.eth_low), Toast.LENGTH_SHORT).show();
                                mEditShowValue = 0.0f;
                            }
                            mEtValue.setText(DataUtils.getFourDecimal(mEditShowValue));
                        } else {
                            mEditShowValue = mLocalValue;
                            mEtValue.setText(DataUtils.getFourDecimal(mEditShowValue));
                        }
                        mClearValue = true;
                    }
                    break;
                case R.id.iv_token_refresh:
                    updateValue();
                    break;
            }
        } catch (Exception e) {
            Log.e(TAG, "onClick failed:" + e.getMessage());
        }
    }

    private void updateValue() {
        APIModule.getApi()
                .querySymbol(UserInfo.get().address, mAssetsModel.id + "")
                .enqueue(new APIListCallBack<AssetsModel>() {
                    @Override
                    protected void onResponseError(APIException e) {

                    }

                    @Override
                    protected void onFailureError(Call<String> call, Throwable t) {

                    }

                    @Override
                    protected void onResponse(List<AssetsModel> response) {
                        try {
                            Log.e("updateValue onResponse", "::" + GsonUtil.toJsonString(response));
                            if (null != response && response.size() == 1) {
                                mAssetsModel.balance = response.get(0).balance;
                                String showValue = DataUtils.getFourDecimal(mAssetsModel.balance);
                                mCurrentBalanceTv.setText(getResources().getString(R.string.current_balance) + showValue);//设置余额
                            }
                        } catch (Exception e) {
                            Log.e(TAG, "updateValue onResponse failed:" + e.getMessage());
                        }

                    }
                });
    }


    /**
     * 判断转账信息是否正确
     */
    private void getTransferInfo() {
        address = mEtToAddress.getText().toString();
        value = mEtValue.getText().toString();
        double gasValue = 0.0f;
        if (mAssetsModel.symbol.equals("ETH")) {
            gasValue = mSeekBarGas.getTransferProgress() * 21000 * 0.000000001f;
        } else {
            gasValue = mSeekBarGas.getTransferProgress() * mGasLimit * 0.000000001f;
        }
        if (TextUtils.isEmpty(address)) {
            Toast.makeText(this, getResources().getString(R.string.transfer_address_null), Toast.LENGTH_SHORT).show();
            return;
        } else if (!SPUtils.isAddress(address)) {
            Toast.makeText(this, getResources().getString(R.string.address_correct_error), Toast.LENGTH_SHORT).show();
            return;
        } else if (address.equals(UserInfo.get().address)) {
            Toast.makeText(this, getResources().getString(R.string.address_equal), Toast.LENGTH_SHORT).show();
            return;
        } else if (TextUtils.isEmpty(value)) {
            Toast.makeText(this, getResources().getString(R.string.transfer_value_null), Toast.LENGTH_SHORT).show();
            return;
        } else if (DataUtils.getDoubleValue(value) > mLocalValue) {
            Toast.makeText(this, getResources().getString(R.string.lack_of_balance), Toast.LENGTH_SHORT).show();
            return;
        } else if (DataUtils.getDoubleValue(value) == 0) {
            Toast.makeText(this, getResources().getString(R.string.input_value_error), Toast.LENGTH_SHORT).show();
            return;
        } else if (gasValue > mEthBalance) {
            Toast.makeText(this, getResources().getString(R.string.eth_low), Toast.LENGTH_SHORT).show();
            return;
        }
        note = mEtContent.getText().toString();

        long time = SeeleFileMap.getLong(address + value);
        if (((System.currentTimeMillis() - time) <= 30 * 60 * 1000)) {
            new AlertDialog.Builder(this)
                    .setTitle(getString(R.string.alert_tips))
                    .setMessage(getString(R.string.alert_transfer_message))
                    .setCancelable(false)
                    .setPositiveButton(getString(R.string.alert_ok), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            showPassowrd();
                        }
                    })
                    .setNegativeButton(getString(R.string.alert_cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    })
                    .create().show();
        } else {
            showPassowrd();
        }
    }

    /**
     * 密码框弹出
     */
    private void showPassowrd() {
        final PwdPopupWindow popupWindow = new PwdPopupWindow(TransferTokenActivity.this);
        popupWindow.showAtLocation(TransferTokenActivity.this);
        popupWindow.setOnPasswordLisenter(new PwdPopupWindow.OnPasswordLisenter() {
            @Override
            public void onInputEnd(String password) {
                mHandler.obtainMessage(Constants.CMD_INPUTPASSWORD_END, password).sendToTarget();
                popupWindow.dismiss();
            }
        });
    }

    private void startQrCode() {
        try {
            if (ContextCompat.checkSelfPermission(TransferTokenActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                // 申请权限
                ActivityCompat.requestPermissions(TransferTokenActivity.this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
                return;
            }
            // 二维码扫码
            // TODO: 需要移除这段代码
            Intent intent = new Intent(this, ScanActivity.class);
            startActivityForResult(intent, Constant.REQ_QR_CODE);
            // TODO: YangJ
        } catch (Exception e) {
            Log.e(TAG, "startQrCode failed:" + e.getMessage());
        }
    }


    /**
     * 转账
     */
    private void onTransfer(String passord) {
        float gasPrice = mSeekBarGas.getTransferProgress();
        Log.i(TAG, "gasPrice:" + gasPrice);
        String sign = "";
        if (this.mSymbolName.equalsIgnoreCase("ETH")) {
            sign = Utils.getTransactionSigned(address, mNonceId, value, gasPrice, passord);
        } else {
            String contract = this.mContactAddress;
            sign = Utils.getTokenTransactionSigned(contract, address, mNonceId, value, gasPrice, mGasLimit, passord);
        }
        sendTranscation(sign, note);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描结果回调
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            Log.i(TAG, "scan result:" + scanResult);
            mQrResultMap = handleQrJson(scanResult);
            mEtToAddress.setText(mQrResultMap.get("WalletAddress"));
            mEtContent.setText(mQrResultMap.get("Custom"));

        } else if (requestCode == Constant.REQ_CONTACT_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            if (null != bundle) {
                String address = bundle.getString(ContactsActivity.class.getSimpleName());
                if (!TextUtils.isEmpty(address)) {
                    mEtToAddress.setText(address);
                }
            }
        }
    }

    private Map<String, String> handleQrJson(String result) {
        Map<String, String> map = new HashMap<String, String>();
        String value;
        try {
            JSONObject obj = new JSONObject(result);
            value = (String) obj.get("Custom");
            map.put("Custom", value);
            value = (String) obj.get("CoinAddress");
            map.put("CoinAddress", value);
            value = (String) obj.get("WalletAddress");
            map.put("WalletAddress", value);
            value = (String) obj.get("CoinName");
            map.put("CoinName", value);
            value = (String) obj.get("CoinSymbolID");
            map.put("CoinSymbolID", value);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
        return map;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                try {
                    // 摄像头权限申请
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        // 获得授权
                        startQrCode();
                    } else {
                        // 被禁止授权
                        Toast.makeText(TransferTokenActivity.this, "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    Log.e(TAG, "REQ_PERM_CAMERA failed:" + e.getMessage());
                }
                break;
        }
    }

    /**
     * 获取nonce id
     */
    private void getNonceId() {
        String fromAddress = UserInfo.get().address;
        Log.i(TAG, "from address:" + fromAddress);
        APIModule.getApi()
                .getNonceid(fromAddress, mSymbolId)
                .enqueue(new APIObjectCallBack<NonceModel>() {
                    @Override
                    protected void onResponse(NonceModel response) {
                        Log.i(TAG, "onResponse");
                        if (response != null) {
                            mNonceId = response.nonceid;
                            Log.i(TAG, "nonceid:" + response.nonceid);
                        }
                    }

                    @Override
                    protected void onResponseError(APIException e) {
                        Log.i(TAG, "onResponseError");
                    }

                    @Override
                    protected void onFailureError(Call<String> call, Throwable t) {
                        Log.i(TAG, "onFailureError");
                    }
                });

    }


    /**
     * 转账
     */
    private void sendTranscation(String signData, String note) {
        Log.i(TAG, "signData:" + signData);
        String baseNote = note;
        if (!TextUtils.isEmpty(note)) {
            baseNote = BaseUtil.makeToBase64(note);
        }
        if (TextUtils.isEmpty(address)) {
            address = mEtToAddress.getText().toString();
        }
        if (TextUtils.isEmpty(value)) {
            value = mEtValue.getText().toString();
        }
        Log.i(TAG, "address:" + address + ", value:" + value + ",baseNote:" + baseNote);
        APIModule.getApi()
                .sendTranscation(signData, mSymbolId, UserInfo.get().address, baseNote, UserInfo.get().getToken(), address, value)
                .enqueue(new APIObjectCallBack<TranscationModel>() {
                    @Override
                    protected void onResponse(TranscationModel response) {
                        //resetValue();
                        Log.i(TAG, "sendTranscation onResponse");
                        if (response != null) {
                            Log.i(TAG, "tscode:" + response.tscode + ",message:" + response.message);
                            //修改数据库
                            mHandler.obtainMessage(Constants.CMD_SENDTRASLATION_SUCCESS, response).sendToTarget();
                        }
                    }

                    @Override
                    protected void onResponseError(APIException e) {
                        Log.i(TAG, "onResponseError");
                        TransferTokenActivity.this.dismissLoadingDialog();
                        showAlertDialog(R.string.transfer_commit_failed, null);
                    }

                    @Override
                    protected void onFailureError(Call<String> call, Throwable t) {
                        Log.i(TAG, "onFailureError");
                        TransferTokenActivity.this.dismissLoadingDialog();
                        showAlertDialog(R.string.transfer_commit_failed, null);
                    }
                });
    }


    //置空Editetxt
    private void resetValue() {
        mEtToAddress.setText("");
        mEtValue.setText("");
        mEditShowValue = 0.0f;
        mEtContent.setText("");
    }


    //TODO
    class ValueTextWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {


        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (!TextUtils.isEmpty(charSequence)) {
                try {
                    double value = DataUtils.getDoubleValue(charSequence.toString());
                    if (value > mLocalValue) {
                        mEtValue.setText(DataUtils.getFourDecimal(mLocalValue));
                        mEditShowValue = mLocalValue;
                    }
                } catch (Exception e) {
                    Log.e(TAG, "onTextChanged exp:" + e.getMessage());
                }
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    }

    /**
     * 获取gas费用
     */
    public void getGasInfo(int symbolid) {
        Log.i(TAG, "getGasInfo");
        APIModule
                .getApi()
                .getGasInfo(symbolid)
                .enqueue(new APIObjectCallBack<GasInfo>() {
                    @Override

                    protected void onResponse(GasInfo response) {
                        mGasLimit = response.gas;
                        mHandler.obtainMessage(Constants.CMD_UPDATE_GASINFO, response.info).sendToTarget();
                    }

                    @Override
                    protected void onResponseError(APIException e) {
                        Log.i(TAG, "onResponseError");
                    }

                    @Override
                    protected void onFailureError(Call<String> call, Throwable t) {
                        Log.i(TAG, "onFailureError");
                    }

                });
    }

    private void setGasInfo(List<GasModel> listsGas) {
        if (listsGas != null && listsGas.size() == 3) {
            mSeekBarGas.setTransferMin(2);
            if (mGasModel.get(2).price > 40) {
                mSeekBarGas.setTransferMax(mGasModel.get(2).price);
            } else {
                mSeekBarGas.setTransferMax(40);
            }
            mGasModel = listsGas;
            putGasInfo(mGasModel);
            mSeekBarGas.setTransferProgress(mGasModel.get(1).price);
            Log.i(TAG, String.format("min:%f,max:%f,progress:%f", mGasModel.get(0).price, mGasModel.get(2).price, mGasModel.get(1).price));
            double floatGas;
            if (mAssetsModel.symbol.equals("ETH")) {
                floatGas = listsGas.get(1).price * 21000 * 0.000000001f;
                if (listsGas.get(1).price < 2) {
                    floatGas = 2 * 21000 * 0.000000001f;
                }
            } else {
                floatGas = listsGas.get(1).price * mGasLimit * 0.000000001f;
                if (listsGas.get(1).price < 2) {
                    floatGas = 2 * mGasLimit * 0.000000001f;
                }
            }
            String sbValue = String.format("%.6f ETH", floatGas);
            setGasValue(listsGas.get(1).price);
        }
    }

    private void putGasInfo(List<GasModel> listGas) {
        SeeleFileMap.putFloat(Constants.GAS_LOW_KEY, 2);
        SeeleFileMap.putFloat(Constants.GAS_STANDARD_KEY, listGas.get(1).price);
        SeeleFileMap.putFloat(Constants.GAS_FAST_KEY, listGas.get(2).price);
    }

    private void loadGasInfo() {
        Log.i(TAG, "loadGasInfo");
        mGasModel = new ArrayList<GasModel>();
        GasModel[] gasModel = new GasModel[3];
        for (int i = 0; i < gasModel.length; i++) {
            gasModel[i] = new GasModel();
        }
        float price = SeeleFileMap.getFloat(Constants.GAS_LOW_KEY);
        gasModel[0].price = (price == 0 ? 2 : price);
        mGasModel.add(gasModel[0]);
        price = SeeleFileMap.getFloat(Constants.GAS_STANDARD_KEY);
        gasModel[1].price = (price == 0 ? 2 : price);
        mGasModel.add(gasModel[1]);
        price = SeeleFileMap.getFloat(Constants.GAS_FAST_KEY);
        gasModel[2].price = (price == 0 ? 40 : price);
        mGasModel.add(gasModel[2]);
        Log.i(TAG, String.format("min:%f,max:%f,progress:%f", mGasModel.get(0).price, mGasModel.get(2).price, mGasModel.get(1).price));
        mSeekBarGas.setTransferMin(2);
        if (mGasModel.get(2).price > 40) {
            mSeekBarGas.setTransferMax(mGasModel.get(2).price);
        } else {
            mSeekBarGas.setTransferMax(40);
        }

        mSeekBarGas.setTransferProgress(mGasModel.get(1).price);

    }

    private void handleQrResult() {
        Bundle bundle = getIntent().getExtras();
        String title = "";
        mEthPrice = SPUtils.getFloat(SPUtils.ETH_PRICE, 0f);
        Log.i(TAG, "mEthPrice:" + String.format("%f", mEthPrice));
//        querySymbol();
        Log.i(TAG, "mEthBalance:" + String.format("%f", mEthBalance));
        String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
        if (scanResult == null) {
            mAssetsModel = (AssetsModel) bundle.getSerializable(TransferTokenActivity.class.getSimpleName());
            title = mAssetsModel.symbol;
            mContactAddress = mAssetsModel.addr;
            mSymbolName = mAssetsModel.symbol;
            mSymbolId = mAssetsModel.id;
            getNonceId();
            mLocalValue = DataUtils.getDoubleValue(mAssetsModel.balance);
            String showValue = DataUtils.getFourDecimal(mAssetsModel.balance);
            mCurrentBalanceTv.setText(getResources().getString(R.string.current_balance) + showValue);//设置余额
            isFormQRcode = false;
        } else {
            Log.i(TAG, "scan result:" + scanResult);
            mQrResultMap = handleQrJson(scanResult);
            mEtToAddress.setText(mQrResultMap.get("WalletAddress"));
            mEtContent.setText(mQrResultMap.get("Custom"));
            title = mQrResultMap.get("CoinName");
            mContactAddress = mQrResultMap.get("CoinAddress");
            mSymbolName = mQrResultMap.get("CoinName");
            mSymbolId = Integer.valueOf(mQrResultMap.get("CoinSymbolID")).intValue();
            mAssetsModel = new AssetsModel();
            mAssetsModel.symbol = mSymbolName;
            isFormQRcode = true;
        }
        setTitle(title);
    }

    private void querySymbol() {
        if (mEthPrice == 0 || mEthBalance == 0) {
            APIModule.getApi()
                    .querySymbol(UserInfo.get().address, "2361")
                    .enqueue(new APIListCallBack<AssetsModel>() {
                        @Override
                        protected void onResponseError(APIException e) {

                        }

                        @Override
                        protected void onFailureError(Call<String> call, Throwable t) {

                        }

                        @Override
                        protected void onResponse(List<AssetsModel> response) {
                            Log.e("onResponse", "::" + GsonUtil.toJsonString(response));
                            if (null != response && response.size() == 1) {
                                AssetsModel assetsModel = response.get(0);
                                if (assetsModel.id == 2361) {
//                                    mEthPrice = assetsModel.price;
//                                    mEthBalance = assetsModel.balance;
                                }
                            }

                        }
                    });
        }
    }


    @Override
    protected void onPause() {
        EventBus.getDefault().post(new RefreshEvent());
        super.onPause();
    }

    class TransferTask extends AsyncTask<Void, Object, Integer> {
        String password = "";

        public TransferTask(String password) {
            this.password = password;
        }

        @Override
        protected void onPreExecute() {
            showLoadingDialog();
        }

        @Override
        protected Integer doInBackground(Void... voids) {
            try {
                String pwd = password + Utils.getSignature().substring(0, 18);
                boolean isOk = EthWalletUtil.checkPassowrd(password);
                if (isOk) {
                    onTransfer(password);
                } else {
                    flag++;
                    return flag;
                }
            } catch (Exception e) {
                Log.e(TAG, "TransferTask doInBackground failed:" + e.getMessage());
            }
            return 0;
        }

        @Override
        protected void onPostExecute(Integer integer) {
            dismissLoadingDialog();
            int flag = integer.intValue();
            switch (flag) {
                case 1:
                    onToast(cout - 1);
                    break;
                case 2:
                    onToast(cout - 2);
                    break;
                case 3:
                    onToast(cout - 3);
                    break;

                case 4:
                    onToast(cout - 4);
                    break;
                case 5:
                    //密码输错5次
                    TransferErrorModel transferErrorModel = new TransferErrorModel();
                    toast();
                    transferErrorModel.isError = true;
                    transferErrorModel.time = System.currentTimeMillis();
                    SPUtils.putString(SPUtils.TRANSFER_TIME, GsonUtil.toJsonString(transferErrorModel));
                    break;
            }

        }

    }

    private void toast() {
        showAlertDialog(R.string.transfer_password_error_time, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
    }

    public void onToast(int count) {
        String message = getResources().getString(R.string.transfer_password_error);
        showAlertDialog(message, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
    }

}
